#nullable enable // 启用可空引用类型检查

using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CsvChartApp
{
    static class Program
    {
        private const string AppName = "带宽分析工具";
        private const string RequiredRuntimeName = "Microsoft.WindowsDesktop.App";
        private static readonly int[] SupportedMajorVersions = { 8, 9 };

        [STAThread]
        static void Main()
        {
            if (!IsAnySupportedRuntimeInstalled())
            {
                ShowRuntimeMissingMessage();
                return;
            }

            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        private static bool IsAnySupportedRuntimeInstalled()
        {
            return IsRuntimeInstalledViaRegistry() || IsRuntimeInstalledViaCli();
        }

        private static bool IsRuntimeInstalledViaRegistry()
        {
            string registryPath = $@"SOFTWARE\dotnet\Setup\InstalledVersions\x64\sharedfx\{RequiredRuntimeName}";
            try
            {
                // OpenSubKey 可能返回 null，所以 key 必须是可空类型
                using (var key = Registry.LocalMachine.OpenSubKey(registryPath))
                {
                    if (key == null) return false;

                    foreach (string versionStr in key.GetValueNames())
                    {
                        if (Version.TryParse(versionStr, out Version? installedVersion) && installedVersion != null)
                        {
                            if (SupportedMajorVersions.Contains(installedVersion.Major))
                            {
                                return true;
                            }
                        }
                    }
                }
            }
            catch { /* 忽略异常 */ }
            return false;
        }

        private static bool IsRuntimeInstalledViaCli()
        {
            try
            {
                var processStartInfo = new ProcessStartInfo
                {
                    FileName = "dotnet",
                    Arguments = "--list-runtimes",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.System)
                };

                // Process.Start 可能返回 null，所以 process 必须是可空类型
                using (var process = Process.Start(processStartInfo))
                {
                    if (process == null) return false;

                    string output = process.StandardOutput.ReadToEnd();
                    process.WaitForExit();

                    using (var reader = new StringReader(output))
                    {
                        string? line; // ReadLine 可能返回 null
                        while ((line = reader.ReadLine()) != null)
                        {
                            string[] parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            if (parts.Length >= 2 && parts[0].Equals(RequiredRuntimeName, StringComparison.OrdinalIgnoreCase))
                            {
                                if (Version.TryParse(parts[1], out Version? installedVersion) && installedVersion != null)
                                {
                                    if (SupportedMajorVersions.Contains(installedVersion.Major))
                                    {
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch { /* 忽略异常 */ }
            return false;
        }

        private static void ShowRuntimeMissingMessage()
        {
            int latestStableVersion = 8;
            string message =
                $"欢迎使用 {AppName}！\n\n" +
                $"此应用程序需要 .NET 桌面运行时 (版本 {string.Join(" 或 ", SupportedMajorVersions)})。\n" +
                "您的系统当前未安装任何受支持的版本。\n\n" +
                $"请点击“确定”按钮访问官方下载页面，下载并安装 .NET {latestStableVersion} Desktop Runtime (x64) 即可。";

            string downloadUrl = $"https://dotnet.microsoft.com/download/dotnet/{latestStableVersion}.0";

            if (MessageBox.Show(message, $"{AppName} - 需要运行环境", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.OK)
            {
                try
                {
                    // Process.Start 可以接受一个 non-nullable 的 string
                    Process.Start(new ProcessStartInfo(downloadUrl) { UseShellExecute = true });
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"无法自动打开浏览器，请手动复制以下链接访问：\n{downloadUrl}\n\n错误信息: {ex.Message}", "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
    }
}